package ext.tianma.db;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import org.apache.log4j.Logger;

import wt.log4j.LogR;
import wt.util.WTProperties;

/**
 * 数据库连接操作类
 * 
 * @author gx
 * 
 */
public class ConnectionFactory {

	private static ConnectionFactory ref = null;
	private static Logger logger = LogR.getLogger(ConnectionFactory.class.getName());

	public static synchronized ConnectionFactory getInstance() {

		if (ref == null) {
			ref = new ConnectionFactory();
		}
		return ref;
	}

	/**
	 * 获取数据库连接对象
	 * @author gx
	 * @return
	 */
	public Connection getConnection() {

		try {
			WTProperties wtproperties = WTProperties.getLocalProperties();

			String propfile = wtproperties.getProperty("wt.home") + File.separator + "db" + File.separator + "db.properties";

			Properties props = new Properties();

			FileInputStream fis = new FileInputStream(propfile);

			props.load(fis);

			fis.close();

			String driver = props.getProperty ("wt.pom.jdbc.driver","oracle.jdbc.driver.OracleDriver");

		    String url = props.getProperty ("wt.pom.jdbc.url","jdbc:oracle:thin:") + "@"
			    + props.getProperty ("wt.pom.jdbc.host") + ":"
			    + props.getProperty ("wt.pom.jdbc.port") + ":"
			    + props.getProperty ("wt.pom.jdbc.service");
		    
		    String username = props.getProperty ("wt.pom.dbUser");

		    String encrypted_value = props.getProperty ("wt.pom.dbPassword");
		   
		    String userpass = com.ptc.windchill.keystore.WTKeyStoreUtil.decryptProperty(username,encrypted_value, wtproperties.getProperty("wt.home"));

		    System.out.println("db info is -> " + " \n url[" + url + "] \n username[" + username + "] \n userpass[" + userpass + "]");

			Class.forName(driver);

			return DriverManager.getConnection(url, username, userpass);

		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			return null;
		}

	}
	

	/**
	 * 关闭ResultSet、Statement、Connection对象
	 * 
	 * @param rs
	 * @param stmt
	 * @param conn
	 */
	public void close(ResultSet rs, Statement stmt, Connection conn) {
		try {
			if (rs != null) {
				rs.close();
			}
			if (stmt != null) {
				stmt.close();
			}
			if (conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}
